Generator Pattern
Learn about the generator pattern in Golang.
We'll cover the following
Overview of the generator pattern#
We use a generator pattern to create a sequence of values that we can use to produce an output. A generator is a function that behaves like an iterator. In other words, it’s a function that launches a goroutine that produces data on a channel that it returns.
1 of 6
2 of 6
3 of 6
4 of 6
5 of 6
6 of 6
Let’s break it down into simple words. Once called, the generator function returns a channel containing the produced data. We use goroutines to implement the generators.
This goroutine (fibonacci) is called a generator in the general case and an iterator when it produces elements of a container. Another goroutine writes to the fibonacci channel. It executes until the channel is closed.
Generator with parallelism#
We can add parallelism to generators as well. When the generator task is computationally expensive, we can create multiple goroutines inside it, but we can’t guarantee the order.
Let’s take a simple example of the generator function with multiple goroutines. If we have some expensive functions, we can call this type of function to take advantage of the power of parallelism.
Execute the code multiple times. Each time, a different output can be observed.
What is a Design Pattern?
Challenge: Write Code with a Generator Pattern